package io.github.jyrmc.gmcp.generate

import io.github.jyrmc.gmcp.common.FreemarkerConstant
import io.github.jyrmc.gmcp.entity.TableEntity
import io.github.jyrmc.gmcp.utils.PrintInfoUtil
import freemarker.template.Configuration
import freemarker.template.Template
import io.github.jyrmc.gmcp.enums.FileStrategyType
import java.io.*
import java.nio.charset.StandardCharsets

/**
 *
 * @描述：生成实体(与数据库表字段一对一)
 * @时间：2021/3/1 5:19 下午
 * @作者：jy
 * @公司：贵州中测信息技术有限公司
 */
object GenerateAddPOJO {

    /**
     * 生成实体-freemarker模板
     */
    fun freemarkerGenerate(
        fileGenStrategy: FileStrategyType,
        frameworkType: String,
        config: Configuration,
        projectPath: String,
        packageName: String,
        dic: String,
        languageType: String,
        tableInfo: TableEntity,
        dataMap: MutableMap<String, Any?>
    ) {
        var fileName =
            "Add${tableInfo.className}POJO.${if (languageType == "java") FreemarkerConstant.JAVA_FILE_SUFFIX else FreemarkerConstant.KOTLIN_FILE_SUFFIX}"
        var fileFullPath =
            "${projectPath}/src/main/${languageType}/${packageName.replace(".", "/")}/pojo/${fileName}"

        var file = File(fileFullPath)
        if (fileGenStrategy == FileStrategyType.CREATE_IF_NOT_EXISTS) {
            if (file.exists()) {
                println("message: file [${fileName}] is exists.")
                return
            }
        } else if (fileGenStrategy == FileStrategyType.COVER) {
            file.delete()
            file.createNewFile()
        } else {
            if (file.exists()) {
                fileName = "Add${tableInfo.className}POJO_${System.currentTimeMillis()}.${if (languageType == "java") FreemarkerConstant.JAVA_FILE_SUFFIX else FreemarkerConstant.KOTLIN_FILE_SUFFIX}"
                fileFullPath = "${projectPath}/src/main/${languageType}/${packageName.replace(".", "/")}/pojo/${fileName}"
            }
            file = File(fileFullPath)
        }

        if (!file.exists()) {
            file.parentFile.mkdirs()

            PrintInfoUtil.printCreateFold(file.parentFile.absolutePath)
        }

        val template: Template = if (languageType == "java") {
            config.getTemplate(
                "java/$frameworkType/${FreemarkerConstant.ADD_POJO_TEMPLATE_JAVA}",
                "UTF-8"
            )
        } else {
            config.getTemplate(
                "kotlin/$frameworkType/${FreemarkerConstant.ADD_POJO_TEMPLATE_KOTLIN}",
                "UTF-8"
            )
        }

        val out: Writer = BufferedWriter(OutputStreamWriter(FileOutputStream(fileFullPath), StandardCharsets.UTF_8))
        template.process(dataMap, out)
        out.flush()
        out.close()

        PrintInfoUtil.printCreateFile(fileFullPath)
    }
}